package servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import connection.DbConnection;

import model.EmailingSystem;
import model.PollUserImpl;
import bean.PollUser;

public class resetServlet extends HttpServlet{

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4048425773991030217L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost (request, response);
	}
	
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html"); 
		response.setCharacterEncoding("GBK");
		System.out.println("resetServletRun");
		
		// Get parameters
		String username = request.getParameter("usernameReset");
		String password = Integer.toString((int)(Math.random()*1000));
		
		// Error checking
		System.out.println("Username: "+username);
		System.out.println("Password: " + password);
		
		// Check for user
		PollUser user = new PollUser();
		user.setUsername(username);
		if (!PollUserImpl.checkUserNameOnly(user)) {
			// Username error
			request.getSession().setAttribute("login_reset_noUser", "t");
			request.getSession().setAttribute("login_reset_success","f");
		} else {
			request.getSession().setAttribute("login_reset_noUser", "f");
			
			// Change password
			user.setPassword(password);
			request.getSession().setAttribute("password", user.getPassword());
			
			// Change in database
			DbConnection db = new DbConnection();
			String sql = "Update PollUser set password='"+user.getPassword()+"' where username='"+user.getUsername()+"'";
			System.out.println(sql);
			db.doUpdate(sql);
			
			// Send change of password email
			EmailingSystem.sendPasswordChange(user);
			
			// Set session success variable
			request.getSession().setAttribute("login_reset_success","t");
			
		}
		response.sendRedirect("login.jsp");
		
		
	}
}
